package com.smedi.ismedi.file.core.port.adapter.persistence.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smedi.ismedi.file.core.domain.aggregatemodel.FileInfo;
import com.smedi.ismedi.file.core.domain.aggregatemodel.FileRepository;
import com.smedi.ismedi.file.core.port.adapter.persistence.model.FileEntity;
import com.smedi.ismedi.file.core.port.adapter.persistence.mybatis.mapper.FileMapper;
import com.smedi.ismedi.web.starter.util.DozerUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Author Jimmy
 * @Date 2021/6/1 13:45
 */
@Repository
@AllArgsConstructor
public class FileRepositoryImpl extends ServiceImpl<FileMapper, FileEntity> implements FileRepository, IService<FileEntity> {

    private final FileMapper fileMapper;

    private final DozerUtil dozerUtil;

    /**
     * {@inheritDoc}
     */
    @Override
    public FileInfo addFileInfo(FileInfo fileInfo) {
        FileEntity fileEntity = dozerUtil.convertor(fileInfo, FileEntity.class);
        this.baseMapper.insert(fileEntity);
        FileInfo file = dozerUtil.convertor(fileEntity, FileInfo.class);
        return file;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public FileInfo getFileBySignKey(String signKey) {

        QueryWrapper<FileEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("sign_key", signKey);
        FileEntity fileEntities = fileMapper.selectOne(wrapper);
        return dozerUtil.convertor(fileEntities, FileInfo.class);
    }

    @Override
    public List<FileInfo> getFileList(List<String> signKeys) {
        LambdaQueryWrapper<FileEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(signKeys),FileEntity::getSignKey,signKeys);
        List<FileEntity> fileEntities = this.baseMapper.selectList(lambdaQueryWrapper);
        return dozerUtil.convertor(fileEntities, FileInfo.class);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean deleteFileBySignKey(String signKey, String reason) {

        int result = fileMapper.deleteFileBySignKey(signKey, reason);
        return result > 0;
    }


}
